package com.gaoyang.util.net.okhttp;

import com.gaoyang.util.net.HttpResult;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Iterator;
import java.util.Map;

public class OkHttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
    private static OkHttpClient okHttpClient = OkHttpConfiguration.getClient();

    static {
        System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
    }

    private OkHttpUtil(){

    }

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static HttpResult get(String url, Map<String, String> queries) {
        HttpResult result = new HttpResult();
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request request = new Request
                .Builder()
                .url(sb.toString())
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .header("Accept-Language", "zh-CN,zh;q=0.8")
                .header("Cache-Control", "no-cache")
                .header("Host", "app.bjzgh12351.org")
                .build();
        Response response = null;
        try {
            long start = System.currentTimeMillis();
            response = okHttpClient.newCall(request).execute();
            long end = System.currentTimeMillis();
            int status = response.code();
            result.setStatus(status);
            result.setCost(end - start);
            if (status == 200) {
                byte[] bytes = response.body().bytes();
                if (bytes != null) {
                    result.setInputStream(new ByteArrayInputStream(bytes));
                }
            }
            logger.info("请求url：{}，结果状态：{}，耗时：{}毫秒。", sb.toString(), status, ((end - start)));
        } catch (Exception e) {
            result.setStatus(HttpResult.STATUS_EXP);
            logger.error("请求url异常：{}", sb.toString(), e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return result;
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static String post(String url, Map<String, String> params) {
        String responseBody = "";
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request
                .Builder()
                .url(url)
                .post(builder.build())
                .build();
        Response response = null;
        try {
            long start = System.currentTimeMillis();
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (status == 200) {
                return response.body().string();
            }
            long end = System.currentTimeMillis();
            logger.info("post请求url：{}，结果状态：{}，耗时：{}毫秒。", url, status, ((end - start)));
        } catch (Exception e) {
            logger.error("post请求url异常：{}", url, e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    /**
     * post 上传文件
     *
     * @param url
     * @param params
     * @param fileType
     * @return
     */
    public static String postFile(String url, Map<String, Object> params, String fileType) {
        String responseBody = "";
        MultipartBody.Builder builder = new MultipartBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                if (params.get(key) instanceof File) {
                    File file = (File) params.get(key);
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
                    continue;
                }
                builder.addFormDataPart(key, params.get(key).toString());
            }
        }
        Request request = new Request
                .Builder()
                .url(url)
                .post(builder.build())
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (status == 200) {
                return response.body().string();
            }
        } catch (Exception e) {
            logger.error("okhttp postFile Exception:{}", url, e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }
}